﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Practice_DotNet.Helper;
using Practice_DotNet.Model;

namespace Practice_DotNet.Operation
{
    internal class UserInfoOperation
    {
        /// <summary>
        /// 将数据行转为数据对象
        /// </summary>
        /// <param name="currentRow"></param>
        /// <returns></returns>

        public static UserInfoModel DataRowToUserInfo(DataRow currentRow)
        {
            UserInfoModel userInfo = new();
            userInfo.Account = currentRow["Account"].ToString() ?? "";
            userInfo.Password = currentRow["Password"].ToString() ?? "";
            userInfo.PetName = currentRow["PetName"].ToString() ?? "";
            userInfo.Gender = Convert.ToInt32(currentRow["Gender"]);
            return userInfo;
        }

        public static async Task<UserInfoModel?> GetUserInfo(string account, string passWord)
        {
            string commandStr = $"SELECT * FROM userinfo where Account = '{account}' and Password = '{passWord}'";
            var result = await SQLHelper.SQL_CRUDOnlyRead(commandStr);
            if (result.Rows.Count > 0)
            {
                return DataRowToUserInfo(result.Rows[0]);
            }
            else return null;
        }
        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static async Task<int> UpdateUserInfo(UserInfoModel userInfo)
        {
            string commandStr = $"""
            UPDATE userinfo set gender = {userInfo.Gender},
            set PetName='{userInfo.PetName},
            set Password='{userInfo.Password}'
            where Account ='{userInfo.Account}' ;
            """;
            if (userInfo != null)
            {
                return await SQLHelper.SQL_CRUDWithoutRead(commandStr);
            }
            else
            {
                throw new ArgumentNullException("userInfo", "userInfo对象不可为空");
            }
        }
        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns></returns>
        public static async Task<List<UserInfoModel>> GetAllUserInfo()
        {
            List<UserInfoModel> userInfos = new List<UserInfoModel>();
            string commandStr = $"""
                Select *
                From userinfo;
                """;
            var result = await SQLHelper.SQL_CRUDOnlyRead(commandStr);
            if (result.Rows.Count > 0)
            {
                for (int i = 0; i < result.Rows.Count; i++)
                {
                    userInfos.Add(DataRowToUserInfo(result.Rows[i]));
                }
            }
            return userInfos;
        }
    }
}
